package com.etc.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import com.etc.entity.Employees;
import com.etc.service.IEmployeesService;
import com.etc.service.impl.EmployeesServiceImpl;
import com.google.gson.Gson;

/**
 * Servlet implementation class employeesController
 */
@WebServlet("/EmployeesController")
@MultipartConfig
public class EmployeesController extends HttpServlet {
	private static final long serialVersionUID = 1L;
       IEmployeesService service=new EmployeesServiceImpl();
       
 
    public EmployeesController() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		String op=request.getParameter("op");
		HttpSession session = request.getSession();
//		Object object = session.getAttribute("emp");
		if("login".equals(op)) {		
			empLogin(request,session,response);
		}else if("updatePic".equals(op)){
			updatePic(request,session,response);
		}else if("getPic".equals(op)) {
			getPic(request,session,response);
		}
	
	}

	//获取头像
	private void getPic(HttpServletRequest request, HttpSession session, HttpServletResponse response) throws IOException {
		//设置存储头像的目录
		String root = "D:\\images\\";
		//获取文件名
		String fileName = request.getParameter("fileName");
		//找到该文件
		File file = new File(root + fileName);
		FileInputStream fis = new FileInputStream(file);
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] bs = new byte[1024];
		int n;
		//读
		while((n = fis.read(bs)) != -1) {
			//写
			bos.write(bs, 0, n);
		}
		fis.close();
		bos.close();
		
		ServletOutputStream outs = response.getOutputStream();
		outs.write(bos.toByteArray());
		outs.flush();
		outs.close();
	}

	//修改头像
	private void updatePic(HttpServletRequest request, HttpSession session, HttpServletResponse response) throws IOException, ServletException {
		response.setContentType("application/json;utf-8");
		Part part = request.getPart("ep");
		String parameter = request.getParameter("username");
		System.out.println(parameter);
		System.out.println("part:" + part);
		PrintWriter writer = response.getWriter();
		if(part == null) {
			return;
		}
		String path = loadPhoto(part, request, response);
		Employees emp = (Employees)session.getAttribute("admin");
		String oldPath = emp.getEmpPicture();
		emp.setEmpPicture(path);
		boolean flag = service.modifyEmpPic(emp);
		if(flag) {
			File file = new File("D:\\images\\" + oldPath);
			if(file.exists()) {
  				file.delete();
  			}
			session.setAttribute("emp", emp);
			Gson gson = new Gson();
			String json = gson.toJson(emp);
			writer.print(json);
		}
		
		writer.close();
	}

	private void empLogin(HttpServletRequest request, HttpSession session, HttpServletResponse response) throws ServletException, IOException {
		String uname = request.getParameter("userName");
		String pwd = request.getParameter("userPwd");
		String code = request.getParameter("code");
		String verifyCode = (String)session.getAttribute("verifyCode");
		Employees emp = service.login(uname, pwd);
		if (verifyCode.equalsIgnoreCase(code) && emp!=null && emp.getEmpStatus()==1) {
				String reme=request.getParameter("autoLogin");
				if (reme!=null) {
					System.out.println("用户选择记住密码"+reme);
					Cookie cookie1=new Cookie("username", uname);
					Cookie cookie2=new Cookie("userpwd", pwd);
					Cookie cookie3=new Cookie("checked","checked" );
					cookie1.setMaxAge(240);
					cookie2.setMaxAge(240);
					cookie3.setMaxAge(240);
					response.addCookie(cookie1);
					response.addCookie(cookie2);
					response.addCookie(cookie3);
				}
				session.setAttribute("emp", emp);
				
				//跳转到前台页面
				response.sendRedirect("front/mysef.jsp");
				System.out.println("登录成功");
		}else {
			//用户名和密码错误,跳转到登录页面去
			//1.转发
			//2.重定向
			session.setAttribute("error_message", "用户名或密码错误,请重试~~");
			response.sendRedirect("login.jsp");
		}
	}
	
	private String loadPhoto(Part part,HttpServletRequest request, HttpServletResponse response) throws IOException {
		//通过请求头和拼接获得真实的图片名
		String header = part.getHeader("content-disposition");
		System.out.println(header);
		String realName=header.substring(header.indexOf("filename=")+10,header.length()-1);
		System.out.println(realName);
		//添加uuid
		UUID uuid = UUID.randomUUID();
		String uuidRealName=uuid+realName;
		System.out.println(uuidRealName);
		//拼接完整文件名
//		String photePath=request.getServletContext().getRealPath("/") + "dist\\img\\" +uuidRealName;
		
		String photePath="D:\\images\\" + uuidRealName;
		System.out.println(photePath);
		//写入文件
		part.write(photePath);
		//此处返回的是文件的路径片段
		return uuidRealName;
}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
